<?php


namespace EasySwoole\EasySwoole;


use App\Models\RequestLog;
use App\Process\QueueProcess;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Db\Connection;
use EasySwoole\ORM\Db\Config;
use EasySwoole\EasySwoole\Config as GlobalConfig;
use EasySwoole\Queue\Driver\RedisQueue;
use EasySwoole\Queue\Job;
use EasySwoole\Queue\Queue;
use EasySwoole\Redis\Config\RedisConfig;
use EasySwoole\Spl\SplBean;
use itbdw\Ip\IpLocation;

class EasySwooleEvent implements Event
{
    public static function initialize()
    {
        date_default_timezone_set('Asia/Shanghai');
        //数据库链接预热,worker启动的是时候，提前准备好链接 突如其来的高并发
        GlobalConfig::getInstance()->loadFile('');
        $config = new Config(GlobalConfig::getInstance()->getConf("MYSQL"));
        DbManager::getInstance()->addConnection(new Connection($config));
        \EasySwoole\Component\Di::getInstance()->set(\EasySwoole\EasySwoole\SysConst::HTTP_EXCEPTION_HANDLER, [\App\Exception\ExceptionHandler::class, 'handle']);

    }

    /**
     * 主服务创建事件
     * @param EventRegister $register
     */
    public static function mainServerCreate(EventRegister $register)
    {
        $register->add($register::onWorkerStart, function () {
            // 链接预热
            // DbManager::getInstance()->getConnection()->getClientPool()->keepMin();

            DbManager::getInstance()->getConnection()->__getClientPool()->keepMin();
        });

        // 配置同上别忘了添加要检视的目录  热加载\
        $hotReloadOptions = new \EasySwoole\HotReload\HotReloadOptions;
        $hotReload = new \EasySwoole\HotReload\HotReload($hotReloadOptions);
        $hotReloadOptions->setMonitorFolder([EASYSWOOLE_ROOT . '/App']);
        $server = ServerManager::getInstance()->getSwooleServer();
        $hotReload->attachToServer($server);

        //注册自定义进程消费队列
        $processConfig = new \EasySwoole\Component\Process\Config([
            'processName' => 'LogQueue', // 设置 自定义进程名称
            'processGroup' => 'Queue', // 设置 自定义进程组名称
            'enableCoroutine' => true, // 设置 自定义进程自动开启协程
        ]);
        \EasySwoole\Component\Process\Manager::getInstance()->addProcess(new QueueProcess($processConfig));
        $register->add($register::onWorkerStart, function ($server, $id) {
            // 配置 Redis 队列驱动器
            $redis = GlobalConfig::getInstance()->getConf("REDIS");
            $redisConfig = new RedisConfig([
                'host' => $redis['host'], // 服务端地址 默认为 '127.0.0.1'
                'port' => $redis['port'], // 端口 默认为 6379
                'auth' => $redis['auth'], // 密码 默认为 不设置
                'db' => $redis['db'], // 默认为 0 号库
            ]);
            $queue = new Queue(new RedisQueue($redisConfig));
            $job = $queue->consumer()->pop();
            // 或者是自定义进程中消费任务(具体使用请看下文自定义进程消费任务完整使用示例)
            $queue->consumer()->listen(function (Job $job) {
                Logger::getInstance()->error(json_encode((new Request())->getHeaders()));
                //写入到数据库
                $jobData = json_decode($job->getJobData(), true);
                $qqwry_filepath = EASYSWOOLE_ROOT.'/static/qqwry.dat';
                $ip_info = json_encode(IpLocation::getLocation($jobData['client_ip'], $qqwry_filepath),JSON_UNESCAPED_UNICODE);
                RequestLog::create([
                    'client_ip' => $jobData['client_ip'],
                    'user_id' => $jobData['user_id'],
                    'tools_id' => $jobData['tools_id'],
                    'ip_info' => $ip_info,
                    'request_params' => $jobData['request_params'],
                    'create_time' => $jobData['create_time']
                ])->save();

            });
        });
    }
}